package com.xiaolong.websocket.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class WebsocketServer {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workGroup;

    private ServerBootstrap serverBootstrap;

    private int port;

    private int timeOut;

    public void run() throws InterruptedException {
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                .channel(ServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new IdleStateHandler(timeOut, timeOut, timeOut, TimeUnit.SECONDS))
                                .addLast(new HttpServerCodec())
                                //以块的形式写
                                .addLast(new ChunkedWriteHandler())
                                //将分段聚合 http如果请求量大会通过多次请求处理
                                .addLast(new HttpObjectAggregator(8192))
                                //如果是访问这个路径，http会升级ws
                                .addLast(new WebSocketConnectBeforeHandler(null,"/ws"))
                                .addLast(new WebSocketServerProtocolHandler("/ws",null,true))
                                .addLast(new ChannelAfterHandler())
                                .addLast(new WebsocketMessageHandle());
                    }
                });
        ChannelFuture sync = serverBootstrap.bind(port).sync();
    }
    public  void stop() throws InterruptedException {
        Future<?> bossFuture = bossGroup.shutdownGracefully().sync();
        Future<?> workFuture = workGroup.shutdownGracefully().sync();
        log.info("ws server stop success");
    }
}
